package main

import (
	"fmt"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"

	"github.com/aws/aws-sdk-go/aws/awserr"
)

func main() {

	sess := session.Must(session.NewSession())
	svc := s3.New(sess)

	result2, err := svc.ListBuckets(nil)

	if err != nil {
		fmt.Printf("Unable to list buckets, %v\n", err)
		sess = session.Must(session.NewSession(&aws.Config{
			Region: aws.String("cn-north-1")}))
		svc = s3.New(sess)
	}

	fmt.Println("Buckets:")

	for _, b := range result2.Buckets {
		fmt.Printf("* %s created on %s\n",
			aws.StringValue(b.Name), aws.TimeValue(b.CreationDate))
	}

	input2 := &s3.ListObjectsV2Input{
		Bucket:  aws.String("xyd-devops"),
		MaxKeys: aws.Int64(2),
	}

	result, err := svc.ListObjectsV2(input2)
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok {
			switch aerr.Code() {
			case s3.ErrCodeNoSuchBucket:
				fmt.Println(s3.ErrCodeNoSuchBucket, aerr.Error())
			default:
				fmt.Println(aerr.Error())
			}
		} else {
			// Print the error, cast err to awserr.Error to get the Code and
			// Message from an error.
			fmt.Println(err.Error())
		}
		return
	}

	for _, i := range result.Contents {
		fmt.Println(aws.StringValue(i.Key))
	}
	fmt.Println(result.Contents)

}
